package com.lagou.config;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@HandlesTypes({WebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        // 存放WebApplicationInitializer实现类
        List<WebApplicationInitializer> initializers = new LinkedList<>();
        if (set != null) {
            for (Class<?> aClass : set) {
                try {
                    if (MyWebApplicationInitializer.class.equals(aClass)) {
                        MyWebApplicationInitializer myWebApplicationInitializer = (MyWebApplicationInitializer) aClass.newInstance();
                        initializers.add(myWebApplicationInitializer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        // 遍历并调用onStartup()
        AnnotationAwareOrderComparator.sort(initializers);
        for (WebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
